<?php
/**
 * 快找设计师助手对话控制器
 */
namespace Beerus\Modules\DesignerFinder\Controllers;

use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Doraemon\service\Member\WxaConfig;
use Doraemon\model\DesignerFinder\UserConsult;
use Doraemon\model\{Designer, Member\WxaModel, Member};
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;

class ConsultController extends Controller
{

    const PAGE_SIZE = 10;

    // 房屋状态
    const HOUSE_STATUS = [
        1 => '毛坯房',
        2 => '精装修',
        3 => '老房重装',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 对话列表
    public function index(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        $search_params = [];
        if (!empty($request['start_time'])) {
            $condition['add_time[>=]'] = $search_params['start_time'] = strtotime($request['start_time']);
        }
        if (!empty($request['end_time'])) {
            $condition['add_time[<=]'] = $search_params['end_time'] = strtotime($request['end_time']);
        }
        if (!empty($request['designer_nick'])) {
            $designer_uid = Member::getUidByNick($request['designer_nick']);
            $condition['designer_uid'] = $search_params['designer_uid'] = $designer_uid;
        }

        $total = UserConsult::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = UserConsult::select('*', $condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $search_params = http_build_query($search_params);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->disableCreateButton();
                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                    $url = url('/admin/DesignerFinder/export_consult?'. $search_params);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出咨询记录</span></a>
                    </div>';
                    $tool->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->date('start_time', '咨询发送开始时间');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->date('end_time', '咨询发送结束时间');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('designer_nick', '设计师昵称')
                            ->placeholder('请输入设计师昵称，此为精确匹配');
                    });
                    $filter->expand();
                });

                $grid->column('id', '咨询ID');
                $grid->column('nick', '咨询人昵称')->display(function() {
                    return Member::getNickByUid($this->uid);
                });
                $grid->column('wechat_nick', '咨询人微信昵称')->display(function() {
                    return WxaModel::getUserNickByUidAndPlatform($this->uid, WxaConfig::LOGIN_TYPE_FIND_DESIGNER_SPEED);
                });
                $grid->column('designer_nick', '设计师昵称')->display(function() {
                    return Member::getNickByUid($this->designer_uid);
                });
                $grid->column('wechat_id', '设计师微信号')->display(function() {
                    return Designer::getWechatIdByUid($this->designer_uid);
                });
                $grid->column('add_time', '发送时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->column('house_space', '房屋面积（平方米）');
                $grid->column('house_budget', '预算（万元）');
//                $grid->column('house_area', '位置')->display(function () {
//                    return Area::locationId2String($this->house_area);
//                });
	            $grid->column('area_name', '位置');
                $grid->column('house_status', '房屋状态')->display(function () {
                    return self::HOUSE_STATUS[$this->house_status];
                });
                $grid->column('phone', '手机号');
                $grid->column('checkin_time', '入住时间')->display(function () {
                    return date('Y-m', $this->checkin_time);
                });
            }
        );

        $tab = new Tab();
        $tab->add('用户咨询列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('用户咨询列表')
            ->description(' ')
            ->breadcrumb(['text' => '用户咨询列表']);
    }

    // 导出咨询记录
    public function exportConsult(Request $request) {
        $request = $request->all();
        if (!empty($request['start_time'])) {
            $request['add_time[>=]'] = $request['start_time'];
            unset($request['start_time']);
        }
        if (!empty($request['end_time'])) {
            $request['add_time[<=]'] = $request['end_time'];
            unset($request['end_time']);
        }
        $lists = UserConsult::select('*', $request);
        $lists = is_array($lists) ? $lists : [];
        $data = [];
        if (!empty($lists)) {
            $user_ids = array_column($lists, 'designer_uid');
            $member_info = Member::getUsers($user_ids);
            foreach ($lists as $item) {
                $data[] = [
                    'id' => $item['id'],
                    'nick' => '用户' . $item['uid'],
                    'designer_uid' => $item['designer_uid'],
                    'designer_nick' => $member_info[$item['designer_uid']]['nick'],
                    'wechat_id' => $wechatId = Designer::getWechatIdByUid($item['designer_uid']),
                    'send_time' => date('Y-m-d H:i:s', $item['add_time']),
                    'house_space' => $item['house_space'],
                    'house_budget' => $item['house_budget'],
//                    'house_area' => Area::locationId2String($item['house_area']),
                    'area_name' => $item['area_name'],
                    'house_status' => self::HOUSE_STATUS[$item['house_status']],
                    'phone' => $item['phone'],
                    'add_time' => date('Y-m-d', $item['add_time'])
                ];
            }
        }
        // 设置列宽
        $header = [
            '咨询ID',
            '咨询人微信昵称',
            '设计师UID',
            '设计师昵称',
            '设计师微信号',
            '发送时间',
            '房屋面积（平米）',
            '预算（万元）',
            '位置',
            '房屋状态',
            '手机号',
            '入住时间'
        ];
        $letter = range('A', 'L');
        $excel_obj = new DownExcel();
        $excel_obj->setFileName('用户咨询列表 - ' . date('YmdHis'));
        $excel_obj->setSheetTitle('用户咨询列表');
        // 设置列宽
        $widths = [
            'A' => 12,
            'B' => 22,
            'C' => 18,
            'D' => 18,
            'E' => 12,
            'F' => 22,
            'G' => 18,
            'H' => 18,
            'I' => 12,
            'J' => 22,
            'K' => 18,
            'L' => 18,
        ];
        $excel_obj->setWidth($widths);
        $excel_obj->setDefaultStyleAlignment();
        foreach ($header as $key => $value) {
            // 设置字体
            $excel_obj->setFrontName($letter[$key]);
            // 设置加粗
            $excel_obj->setFrontBold("$letter[$key]1");
            // 设置大小
            $excel_obj->setFrontSize($letter[$key]);
        }
        $excel_obj->create($data, $header);
    }
}
